<template>
  <common-list>
    <!-- <el-card> -->
    <!-- 头部搜素start -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="query"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
        label-width="98px"
      >
        <el-form-item label="数据库/索引名" prop="databaseName">
          <common-input
            v-model="query.databaseName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数据源名称" prop="datasoureName">
          <common-input
            v-model="query.datasoureName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="数据源类型" prop="datasourceType">
          <el-select v-model="query.datasourceType" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="(item, index) in dbType"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="连接状态" prop="status">
          <el-select v-model="query.status" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="无效" value="1"></el-option>
            <el-option label="有效" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="IP地址" prop="ip">
          <common-input v-model="query.ip" clearable @enter="handleQuery" />
        </el-form-item>

        <common-dept
          ref="commonDept"
          :currentParent="currentParent"
          @getDeptId="getDeptId"
          @getDeptList="getDeptList"
          @getLoading="getLoading"
        ></common-dept>
      </el-form>
    </common-search>
    <!-- 头部搜素end -->

    <!-- 按钮部门start -->
    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="edit(null)"
          plain
          v-hasPermi="['system:datasource:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['system:datasource:delete']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>
    <!-- 按钮部门end -->

    <!--列表 start-->
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        label="数据源名称"
        align="left"
        prop="datasoureName"
        show-overflow-tooltip
        fixed
        width="150"
      >
        <template slot-scope="{ row }">{{ row.datasoureName }}</template>
      </el-table-column>

      <el-table-column
        label="数据源类型"
        align="left"
        prop="datasourceType"
        width="150"
      >
        <template slot-scope="{ row }"
          >{{ findDictLabel(dbType, row.datasourceType, "--") }}
        </template>
      </el-table-column>

      <el-table-column
        label="IP地址"
        align="left"
        prop="ip"
        width="160"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">{{ row.ip }}</template>
      </el-table-column>

      <el-table-column label="端口" align="left" prop="port" width="80">
        <template slot-scope="{ row }">{{ row.port }}</template>
      </el-table-column>

      <el-table-column
        label="数据库/索引名"
        align="left"
        prop="databaseName"
        width="190"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="用户名" align="left" prop="username" width="120">
        <template slot-scope="{ row }">{{ row.username }}</template>
      </el-table-column>

      <el-table-column
        label="组织"
        align="left"
        prop="deptName"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column label="连接状态" align="center" prop="status">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status == 0">有效</el-tag>
          <el-tag type="danger" v-else>无效</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="left" width="270px" fixed="right">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            @click="test(row.id)"
            v-hasPermi="['system:datasource:test']"
            >测试连接
          </el-button>
          <el-button
            type="text"
            @click="config(row)"
            v-if="row.datasourceType === 'ES' ? true : false"
            v-hasPermi="['system:datasource:indexmgr']"
            >索引管理
          </el-button>
          <el-button
            type="text"
            @click="updatePassword(row.id)"
            v-hasPermi="['system:datasource:updatepwd']"
            >修改密码
          </el-button>
          <el-button
            type="text"
            @click="edit(row)"
            v-hasPermi="['system:datasource:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(row)"
            v-if="row.isDefault === 0"
            v-hasPermi="['system:datasource:delete']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />
    <!-- </el-card> -->
    <!-- 列表 end -->
    <editDialog
      ref="editDialog"
      :isEs="flag"
      @refresh="getList"
      :deptListParams="deptListParams"
    />
    <common-edit-dialog
      title="修改密码"
      :visible="isDialog"
      @cancel="cancel"
      @submit="submitForm"
      width="400px"
      :button-loading="pwdLoading"
    >
      <el-form
        ref="passwordForm"
        label-width="73px"
        :model="passwordForm"
        :rules="rules"
        @submit.native.prevent
      >
        <el-form-item label="修改密码" prop="password">
          <common-pwd-input
            placeholder="请输入"
            style="width: 100%"
            v-model="passwordForm.password"
          ></common-pwd-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <common-pwd-input
            :type="'password'"
            placeholder="请输入"
            v-model="passwordForm.password2"
          ></common-pwd-input>
        </el-form-item>
      </el-form>
    </common-edit-dialog>
    <repertoty ref="repertoty" v-if="repertoty" @back="repertoty = false" />
  </common-list>
</template>

<script>
// import configView from "./components/configView.vue";
import editDialog from "./components/editDialog";
import Repertoty from "./components/repertoty";
import { getSingleArray, getFullDept } from "@/utils/util";
import {
  db_edit,
  db_list,
  db_remove,
  db_test,
  getColumnsByTypeList,
  editPwd,
  getIndexId,
  deleteForCheck,
  editForCheck,
} from "@/api/management/echart/db.js";

import { mapState } from "vuex";
import BaseList from "@/mixins/BaseList";
import { encode } from "@/utils/aesUtils";

export default {
  mixins: [BaseList],
  components: { editDialog, Repertoty },
  props: {},
  data() {
    const checkConsistent = (rule, value, callback) => {
      if (value !== this.passwordForm.password) {
        callback(new Error("两次密码不一致！"));
      } else {
        callback();
      }
    };
    return {
      pwdLoading: false,
      flag: false,
      repertoty: false,
      showSearch: true, // 查询部分显示
      total: 0, // 总条数
      loading: false, // table 加载中
      list: [], // 数据列
      selectionIds: "", // 列表选中数据id
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      query: {
        pageNum: 1,
        pageSize: 10,
        datasoureName: "",
        datasourceType: null,
        status: null,
        databaseName: null,
        deptIds: null,
      }, // 查询条件
      isDialog: false,
      passwordForm: {
        id: null,
        password: null,
        password2: null,
      },
      rules: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        password2: [
          { required: true, validator: checkConsistent, trigger: "blur" },
        ],
      },
      currentParent: 1,
      singleDeptList: [],
      deptListParams: [],
    };
  },
  watch: {},
  computed: {
    ...mapState({
      dbType: (state) => state.dict.dbType,
    }),
  },
  methods: {
    getLoading() {
      this.loading = true;
    },
    getDeptList(list) {
      this.deptListParams = list;
      this.singleDeptList = getSingleArray(list);
      this.getList();
    },
    getDeptId(val) {
      this.query.deptIds = val;
    },
    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },

    // 修改密码
    updatePassword(id) {
      editForCheck({ id }).then((res) => {
        if (res && res.code === 200) {
          if (res.data.length) {
            this.$GlobalDeleteConfirm(
              `该数据源已被${res.data.length}个数据集关联，如若修改，已关联数据集会损坏需重新配置。确认修改吗？`
            )
              .then(() => {
                this.passwordForm.id = id;
                this.isDialog = true;
              })
              .catch(() => {});
          } else {
            this.passwordForm.id = id;
            this.isDialog = true;
          }
        }
      });
    },
    //取消按钮
    cancel() {
      this.isDialog = false;
      this.restForm();
    },
    //修改密码提交
    submitForm() {
      // 校验表单
      this.$refs["passwordForm"].validate((valid) => {
        if (valid) {
          this.pwdLoading = true;
          editPwd({
            password: encode(this.passwordForm.password),
            id: this.passwordForm.id,
          })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("修改成功");
                this.getList();
              } else {
                this.$GlobalErrorConfirm("修改失败", res.msg);
              }
            })
            .finally(() => {
              this.isDialog = false;
              this.pwdLoading = false;
            });
        }
      });
    },
    restForm() {
      this.passwordForm.password = null;
      this.passwordForm.password2 = null;
    },

    /**
     * 选择
     */
    handleSelectionChange(selection) {
      this.selectionIds = selection.map((item) => item.id).join(",");
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /**
     * 获取列表
     */
    getList() {
      this.loading = true;
      db_list({ ...this.query })
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows;
            this.list.forEach((item) => {
              item.deptName = this.getDeptName(item.deptId || "");
            });
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    config(row) {
      const data = {
        id: row.id,
        ip: row.ip,
        port: row.port,
        indexPrefix: row.databaseName,
      };
      this.repertoty = true;
      this.$nextTick(() => {
        this.$refs.repertoty.show(data);
      });
      // let data = {
      //   indexPrefix: row.databaseName,
      //   ip: row.ip,
      //   port: row.port,
      // };
      // getIndexId(data).then((res) => {
      //   if (res && res.code === 200) {
      //     if (res.msg) {
      //       console.log(res.msg);
      //       this.repertoty = true;
      //       this.$nextTick(() => {
      //         this.$refs.repertoty.show(data, res.msg);
      //       });
      //     } else {
      //       this.$GlobalErrorConfirm("提示", "字段无索引配置");
      //     }
      //   }
      // });
    },
    /**
     * 查询
     */
    handleQuery() {
      this.query.pageNum = 1;
      this.getList();
    },
    /**
     * 重置查询
     */
    resetQuery() {
      this.query = this.$options.data().query;
      this.$refs.commonDept.clearDept();
    },
    /**
     * 添加/编辑
     */
    edit(row) {
      // console.log("row===>", row);
      if (row) {
        editForCheck({ id: row.id }).then((res) => {
          if (res && res.code === 200) {
            if (res.data.length) {
              this.$GlobalDeleteConfirm(
                `该数据源已被${res.data.length}个数据集关联，如若修改，已关联数据集会损坏需重新配置。确认修改吗？`
              )
                .then(() => {
                  this.$refs.editDialog.show(row ? { ...row } : {});
                  this.flag = !!(
                    row?.datasourceType === "ES" &&
                    row?.id &&
                    row?.status == 0
                  );
                })
                .catch(() => {});
            } else {
              this.$refs.editDialog.show(row ? { ...row } : {});
              this.flag = !!(
                row?.datasourceType === "ES" &&
                row?.id &&
                row?.status == 0
              );
            }
          }
        });
      } else {
        this.$refs.editDialog.show(row ? { ...row } : {});
        this.flag = !!(
          row?.datasourceType === "ES" &&
          row?.id &&
          row?.status == 0
        );
      }
    },

    /**
     * 删除
     */
    deleteData(row) {
      const ids = row?.id || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          db_remove({ ids: ids }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.query.pageNum > 1 &&
                ids.split(",").length === this.list.length
              ) {
                this.query.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg).then();
            }
          });
        })
        .catch(() => {});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        if (
          !ids
            .split(",")
            .every(
              (item) => this.list.find((f) => f.id === item)?.isDefault === 0
            )
        ) {
          reject({
            msg: "预装数据源无法删除！",
          });
        } else {
          deleteForCheck({ ids: ids })
            .then((res) => {
              if (res && res.code === 200) {
                resolve(res);
              } else {
                reject(res);
              }
            })
            .catch((err) => {
              reject(err);
            });
        }
      });
    },
    /**
     * 测试
     */
    test(id) {
      this.$confirm("确定要进行测试吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        db_test({ id: id })
          .then((res) => {
            if (res && res.code === 200) {
              this.getList();
              this.$GlobalSuccessMessage("测试成功");
            } else {
              this.$GlobalErrorConfirm("测试失败", res.msg).then();
            }
          })
          .finally(() => this.getList());
      });
    },
  },
  created() {
    // this.getList();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped></style>
